"""
Differential Evolution
"""

from sko.DE import DE
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Step1：define the problem

def objective_function(x):
    x1, x2, x3 = x
    return 2*x1 + 3*x1**2 + 3*x2 + x2**2 + x3


constraints_eq = [
    lambda x: x[0]**2 + x[2] - 2
]

constraints_ueq = [
    lambda x: x[0] + 2*x[0]**2 + x[1] + 2*x[1]**2 + x[2] - 10,
    lambda x: x[0] + x[0]**2 + x[1] + x[1]**1 - x[2] - 50,
    lambda x: 2*x[0] + x[0]**2 + 2*x[1] + x[2] - 40,
    lambda x: 1 - (x[0] + 2*x[1]),
]

# Step2: do Differential Evolution
de = DE(func=objective_function, n_dim=3, size_pop=50, max_iter=800, lb=[0, 0, 0], ub=[
        5, 5, 5], constraint_eq=constraints_eq,  constraint_ueq=constraints_ueq)
best_x, best_y = de.run()
print('best_x:', best_x, '\n', 'best_y:', best_y)

# Step3: plot the result
Y_history = pd.DataFrame(de.all_history_Y)
plt.figure(figsize=(10, 6), dpi=128)
plt.plot(Y_history.index, Y_history.values, '.', color='red')
Y_history.min(axis=1).cummin().plot(kind='line')
plt.title('Differential Evolution')
plt.savefig('第12章：现代优化算法/DE.png')
plt.show()